/**
 * Created by Administrator on 2017/7/20.
 */
import Config from '../config'
import Storage from '../storage'
export const LOGIN = 'LOGIN'
export const LOGIN_ERROR = 'LOGIN_ERROR'
// import {alert} from './message'
export function loginFetch(username,password,redirect) {
  return dispatch => {
    fetch(Config.loginUrl, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Basic YWNtZTphY21lc2VjcmV0'
      },
      body: `username=${username}&password=${password}&grant_type=password`,
    }).then( (response) => response.json())
    .then( (data) => {
      if(!data.error) {
        Storage.put('custId',data.custId)
        Storage.put('token', data.access_token)
        dispatch(login(data_access_token))
        if(redirect) {
          redirect()
        }
      }else {
        dispatch(alert('账号或密码错误'))
      }
    })
    .catch(function (ex) {
      console.log(ex)
    })
  }
}
export const loginError = (message) => {
  return {
    type: LOGIN_ERROR,
    message
  }
}
export const login = (token) => {
  return {
    type: LOGIN,
    token
  }
}

export function logoutFetch(redirect) {
  return dispatch => {
    fetch('./json/home.json',{
      method: 'get'
    })
    .then( (response) => {
      Storage.clear();
      dispatch(login(''))
      if(redirect) {
        redirect()
      }
    }).catch(function (ex) {
      console.log(ex)
    })
  }
}




















